package com.xyz.frame.api.service.impl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.xyz.frame.api.service.OssService;
import com.xyz.frame.api.service.SzyOssService;
import com.xyz.utils.ConstantPropertiesUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Objects;
import java.util.UUID;

/**
 * @author zsr
 * @date 2021/6/9 21:17
 */
@Service
public class OssServiceImpl implements OssService {
    // 图片类型
    private static String TYPESTR[] = {".png", ".jpg", ".bmp", ".gif", ".jpeg"};


    @Value("${serverIp}")
    private String serverIp;

    @Value("${localPath}")
    private String localPath;


    @Value("${spring.profiles.active}")
    private String profile;

    @Autowired
    private SzyOssService szyOssService;

    //上传图片到Oss
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = ConstantPropertiesUtils.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        InputStream inputStream = null;
        OSS ossClient = new OSSClientBuilder().build(
                endpoint,
                accessKeyId,
                accessKeySecret);
        try {

            boolean flag = false;
            // 判断 文件格式
            for (String type : TYPESTR) {
                if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                return "图片格式不正确";
            }
            // 判断文件内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image != null) {
                /*System.err.println(String.valueOf(image.getHeight()));
                System.err.println(String.valueOf(image.getWidth()));*/
            } else {
                return "文件内容不正确";
            }

            // 创建OSSClient实例。
            inputStream = file.getInputStream();

            //获取文件名称
            String fileName = file.getOriginalFilename();
            //1 在文件名称里面添加随机唯一的值
            String newName = UUID.randomUUID().toString().replaceAll("-", "") + fileName;
            //2 把文件按照日期进行分类
            String datePath = new org.joda.time.DateTime().toString("yyyy/MM/dd");
            String urlPath = ConstantPropertiesUtils.FILE_HOST + "/" + datePath + "/" + newName;

            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(bucketName, urlPath, inputStream);

            return "https://" + bucketName + "." + endpoint + "/" + urlPath;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }

    }
    //上传图片到服务器目录：/Users/gds/project2025/tmp/eduUpload/images/
    //文件名称使用时间戳代替
    //返回图片路径：http://127.0.0.1:8000/tmp/upload/images/2021/06/09/xxxx.png
    @Override
    public String uploadFileAvatarLocal(MultipartFile file) {
        if (!Objects.equals(profile, "prod")) {
            return szyOssService.uploadFileAvatarLocal(file, profile);
        }

        try {
            // 判断文件格式
            boolean flag = false;
            for (String type : TYPESTR) {
                if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                return "图片格式不正确";
            }

            // 判断文件内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                return "文件内容不正确";
            }

            // 创建本地目录
            String datePath = new DateTime().toString("yyyy/MM/dd");
            String path = "/shzhyun/szyoss" + localPath + "/images/" + datePath;
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 使用时间戳生成文件名
            String timestamp = String.valueOf(System.currentTimeMillis());
            String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String newFileName = timestamp + extension;

            // 保存文件到本地
            File localFile = new File(path + "/" + newFileName);
            file.transferTo(localFile);

            // 返回完整的访问URL
            return "https://www.szytech.com/szyoss" + localPath + "/images/" + datePath + "/" + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void getLocalImage(String localPath, HttpServletResponse response) throws IOException {
        try {
            // 创建文件对象
            File file = new File(localPath);

            // 检查文件是否存在
            if (!file.exists()) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
                return;
            }

            // 设置响应头
            response.setContentType("image/jpeg"); // 根据实际图片类型设置
            response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

            // 读取文件并写入响应流
            Files.copy(file.toPath(), response.getOutputStream());
            response.flushBuffer();
        } catch (IOException ex) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error reading file");
        }
    }

    @Override
    public void getLocalVideo(String localPath, HttpServletResponse response) throws IOException {
        try {
            // 创建文件对象
            File file = new File(localPath);

            // 检查文件是否存在
            if (!file.exists()) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Video not found");
                return;
            }

            // 设置响应头
            response.setContentType("video/mp4"); // 根据实际视频类型设置
            response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

            // 读取文件并写入响应流
            Files.copy(file.toPath(), response.getOutputStream());
            response.flushBuffer();
        } catch (IOException ex) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error reading video file");
        }
    }

    @Override
    public String uploadCourseFile(MultipartFile file) {
        try {
//            // 判断文件格式
//            boolean flag = false;
//            for (String type : TYPESTR) {
//                if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
//                    flag = true;
//                    break;
//                }
//            }
//            if (!flag) {
//                return "图片格式不正确";
//            }

            // 判断文件内容
//            BufferedImage image = ImageIO.read(file.getInputStream());
//            if (image == null) {
//                return "文件内容不正确";
//            }

            // 创建本地目录
            String datePath = new org.joda.time.DateTime().toString("yyyy/MM/dd");
            String path = localPath+"/courseFiles/" + datePath;
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 使用时间戳生成文件名
            String timestamp = String.valueOf(System.currentTimeMillis());
            String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String newFileName = timestamp + extension;

            // 保存文件到本地
            File localFile = new File(path + "/" + newFileName);
            file.transferTo(localFile);

            // 返回完整的访问URL
            return serverIp+":8086/api4xyz/eduoss/fileoss/getLocalFile" + path + "/" + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void getLocalFile(String localPath, HttpServletResponse response) throws IOException {
        try {
            // 创建文件对象
            File file = new File(localPath);

            // 检查文件是否存在
            if (!file.exists()) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "file not found");
                return;
            }

            // 设置响应头
            response.setContentType("application/pdf"); // 根据实际文件类型设置
            response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

            // 读取文件并写入响应流
            Files.copy(file.toPath(), response.getOutputStream());
            response.flushBuffer();
        } catch (IOException ex) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error reading video file");
        }
    }

}
